package sucre

class DivisionController {

    def loginService
        def beforeInterceptor = [action:this.&auth]
        def auth = {
            def result =loginService.validarAcceso(
                session["seguridad_usuario"],
                session["seguridad_funcionesHabilitadas"],
                controllerName,actionName,request.getRemoteAddr().toString())
            if(!result) {
                redirect(controller:"login",action:"auth",params:['acceso':false])
                return false
            }
        }
    def index = {}
    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def parametersService
    def list = {
        params.max = parametersService.getInt("paginacion.maxRegPagina")
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        
        def query={
            if(params.searchField){
                ilike('nombre','%'+params.searchField+'%')
            }
            order("nombre", "desc")
        }
        
        def divisionList = Division.createCriteria().list(params,query)
        
        [ divisionInstanceList:  divisionList,
            divisionInstanceTotal: divisionList.getTotalCount()]
    }
    def create = {
        def listaA = []
        def listaB = []
        def divisionInstance = new Division()
        
        
        listaA = Materia.listOrderByNombre()
        divisionInstance.properties = params
        
        if(params.eOc=='edit'){
            divisionInstance = Division.findById(params.id)
            listaB = FormatUtils.sortItems(divisionInstance.materias,"nombre")
            listaB.each{
                listaA.	remove(it)
            }
        }else{
            flash.message=''
            params.eOc='create'
        }
        
        
        return [divisionInstance:divisionInstance,eOc:params.eOc, listaA:listaA, listaB:listaB]
    }
    def save = {
        def listaErrores=[]
        println  "------------------paramsdivision: " + params
        
        def especialidad = Especialidad.get(params.especialidad)
        params.especialidad = especialidad
        if(params.eOc == 'create'){
            params.nombre = params.nombre + "-" + especialidad.nombre
        }
        def divisionInstance = new Division(params)
        if(params.eOc == 'edit'){
            println "params.id: " + params.id
            divisionInstance=Division.get(params.id)
            divisionInstance.properties=params
        }
        //--------------para asociar a aldeas-----------------------------------
        divisionInstance.materias = []
        def cadenaMaterias = params.materias_SB
        if(cadenaMaterias != "" && cadenaMaterias != " " && !cadenaMaterias.contains(",")){
            println "--------no tiene coma agrego una sola materia: "
            divisionInstance.addToMaterias(Materia.get(cadenaMaterias))
        } else if(cadenaMaterias.contains(",")){
            cadenaMaterias = params.materias_SB.split(",")
            cadenaMaterias.each { materia ->
                println "----------tiene coma agrego varias materias: "
                divisionInstance.addToMaterias(Materia.get(materia))
            }
        } else {
            println ".......remuevo aldeas"
            if(divisionInstance.materias != null) {
                divisionInstance.materias.clear()
            }
        }
        Division.withTransaction{ status ->
            try{
                if(!divisionInstance.hasErrors() && divisionInstance.save(flush:true)) {

                    if(params.eOc=='create'){
                        // def.division.creado
                        flash.message=message(code:'def.registro.creado',
                            args:[divisionInstance])
                    }else{
                        //def.division.actualizado
                        flash.message=message(code:'def.registro.actualizado',
                            args:[divisionInstance])
                    }
                        
                    if(params.eOc=='create'){
                        params.eOc='edit'
                    }
                }
            }catch(Exception e){
                println e
                listaErrores.add(message(code:'def.registro.error.Creando'))
                status.setRollbackOnly()
            }
        }
        def listaA = []
        def listaB = []
        listaA = Materia.listOrderByNombre()
        listaB = FormatUtils.sortItems(divisionInstance.materias,"nombre")
        listaB.each{
            listaA.	remove(it)
        }
        render(view:'create',model:[divisionInstance:divisionInstance,
                eOc:params.eOc,upd:'si',listaErrores:listaErrores,listaA:listaA,listaB:listaB])
    }
    def search={
        redirect(action:list,params:[searchField:params.searchField])
    }
    def delete = {
        def listaErrores=[]
        def divisionInstance = Division.get(params.id)
        flash.message=message(code:'def.noeliminado', args:[divisionInstance])
        render(view:'create',model:[divisionInstance:new Division(),upd:'si',
               listaErrores:listaErrores])
    }
}
